package com.lpssfxy.service.impl;

import com.lpssfxy.bean.R;
import com.lpssfxy.entity.*;
import com.lpssfxy.dao.ProductRepository;
import com.lpssfxy.dao.RatingRepository;
import com.lpssfxy.dao.UserRepository;
import com.lpssfxy.service.ABTestRatingService;
import com.lpssfxy.service.RedisService;
import com.lpssfxy.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class ABTestRatingServiceImpl implements ABTestRatingService {

    @Autowired
    private RatingRepository ratingRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisService redisService;

    @Override
    public R addRating() {
        List<User> userList = userRepository.findAll();
        List<Product> productList = productRepository.findAll();
        Random random = new Random();

        int userRandom = random.nextInt(userList.size());
        int productRandom = random.nextInt(productList.size());
        int scoreRandom = random.nextInt(5) + 1;

        int userId = userList.get(userRandom).getUserId();
        int productId = productList.get(productRandom).getProductId();
        Integer timestamp = (int) (System.currentTimeMillis() / 1000);

        // 使用 MongoTemplate 的 findOneAndUpdate 方法进行原子性更新或插入
        Query query = new Query(Criteria.where("userId").is(userId).and("productId").is(productId));
        Update update = new Update()
                .set("score", (double) scoreRandom)
                .set("timestamp", timestamp);

        Rating updatedRating = mongoTemplate.findAndModify(query, update,
                new org.springframework.data.mongodb.core.FindAndModifyOptions().upsert(true).returnNew(true),
                Rating.class);
        // 更新redis
        updateRedis(updatedRating);
        // 埋点：记录用用户打分行为
        log.info(Constant.PRODUCT_RATING_PREFIX + ":{}|{}|{}|{}", updatedRating.getUserId().intValue(), updatedRating.getProductId().intValue(), updatedRating.getScore().intValue(), timestamp);
        return R.ok().message("打分完成！！");
    }

    private void updateRedis(Rating rating) {
        if (redisService.exists("userId:" + rating.getUserId()) && redisService.llen("userId:" + rating.getUserId()) >= Constant.REDIS_PRODUCT_RATING_QUEUE_SIZE) {
            redisService.rpop("userId:" + rating.getUserId());
        }
        String key = "userId:" + rating.getUserId();
        String value = rating.getProductId() + ":" + rating.getScore();
        redisService.leftPush(key.trim(), value.trim());
    }
}